<?php
namespace app\system\controller;

class Region extends Common
{
    protected $pageSize = 20;

    public function index($id=0, $type='')
    {
        $type = trim($type);
        $id = intval($id);
        $t = '';
        if ($type == 'city') {
            $list = $this->city($id);
            $t = 'area';
        } else if ($type == 'area') {
            $list = $this->area($id);
        } else {
            $list = $this->province();
            $t = 'city';
            $type = 'index';
        }


        $assign = [
            'list' => $list,
            't' => $t,
            'type' => $type
        ];
        return $this->fetch($type, $assign);
    }

    protected function province()
    {
        return $this->getList(0);
    }

    /**
     * @param $pid
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\Exception
     */
    protected function city($pid)
    {
        if ($pid <= 0) {
            $this->redirect('index', '数据错误');
        }

        $list = $this->getList($pid);

        $regionModel = new \app\common\model\Region();
        if (!session('?region.province') || session('region.province')['id'] != $pid) {
            session('region.province', $regionModel->findRegion(['id' => $pid], 'id,title')->toArray());
        }
        return $list;
    }

    /**
     * @param $pid
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\Exception
     */
    protected function area($pid)
    {
        if ($pid <= 0) {
            $this->redirect('index', '数据错误');
        }

        $list = $this->getList($pid);

        $regionModel = new \app\common\model\Region();
        if (!session('?region.city') || session('region.city')['id'] != $pid) {
            session('region.city', $regionModel->findRegion(['id' => $pid], 'id,title')->toArray());
        }
        return $list;
    }

    /**
     * 获取区域列表
     * @param $pid
     * @return false|\PDOStatement|string|\think\Collection
     */
    protected function getList($pid)
    {
        $regionModel = new \app\common\model\Region();
        $list = $regionModel->selectRegion(['pid'=>$pid]);
        foreach ($list as &$v){
            $v->count = $regionModel->countRegion(['pid'=>$v->id]);
        }
        return $list;
    }

    public function savesort()
    {
        if (isAjaxPost()) {
            $post = input('post.');
            $regionModel = new \app\common\model\Region();
            foreach ($post as $k=>$v) {
                if ($k > 0) {
                    $regionModel->updateRegion(['sort'=>$v], ['id'=>$k]);
                }
            }
            return $this->jsonSuccess('修改成功');
        }

        return $this->jsonError('非法操作');
    }

    public function del()
    {
        !isAjaxPost() && die();
        $id = input('post.id', 0, 'intval');
        $regionModel = new \app\common\model\Region();
        if ($regionModel->countRegion(['pid'=>$id, 'isDelete'=>0]) > 0) {
            return $this->jsonError('该区域拥有子区域，请先删除子区域');
        }

        if ($regionModel->deleteRegion(['id'=>$id])) {
            return $this->jsonSuccess('删除成功');
        } else {
            return $this->jsonError('删除失败');
        }
    }

    public function add($type='')
    {
        switch ($type) {
            case 'city' :
                $what = '市';
                $pid = session('region.province')['id'];
                break;
            case 'area' :
                $what = '区';
                $pid = session('region.city')['id'];
                break;
            default :
                $what = '省';
                $pid = 0;
                break;
        }

        if (isAjaxPost()) {
            $data = input('post.');

            if (strlen($data['title']) == 0) {
                return $this->jsonError("请输入{$what}名称");
            }
            $data['sort'] = intval($data['sort']);
            $addData = [
                'title' => $data['title'],
                'sort' => intval($data['sort']),
                'pid' => $pid,
                'firstheavy' => '',
                'firstheavyprice' => '',
                'continuedheavy' => '',
                'continuedheavyprice' => '',
                'isDelete' => 0
            ];
            $regionModel = new \app\common\model\Region();
            if ($regionModel->addRegion($addData)) {
                return $this->jsonSuccess('添加成功');
            } else {
                return $this->jsonError('添加失败');
            }
        }

        $assign = [
            'what' => $what,
            'type' => $type,
            'pid' => $pid
        ];
        return $this->fetch('', $assign);
    }

    /**
     * @param $id
     * @param string $type
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     */
    public function save($id, $type='')
    {
        $id = intval($id);
        if ($id < 0) {
            $this->error('参数错误');
        }
        switch ($type) {
            case 'city' :
                $what = '市';
                $pid = session('region.province')['id'];
                break;
            case 'area' :
                $what = '区';
                $pid = session('region.city')['id'];
                break;
            default :
                $what = '省';
                $pid = 0;
                break;
        }

        $regionModel = new \app\common\model\Region();

        if (isAjaxPost()) {
            $data = input('post.');

            if (strlen($data['title']) == 0) {
                return $this->jsonError("请输入{$what}名称");
            }
            $data['sort'] = intval($data['sort']);
            $addData = [
                'title' => $data['title'],
                'sort' => intval($data['sort']),
            ];

            if ($regionModel->updateRegion($addData, ['id'=>$id]) !== false) {
                return $this->jsonSuccess('修改成功');
            } else {
                return $this->jsonError('修改失败');
            }
        }

        $data = $regionModel->findRegion(['id'=>$id])->toArray();
        if (empty($data)) {
            $this->error('区域信息不存在');
        }

        $assign = [
            'what' => $what,
            'type' => $type,
            'data' => $data,
            'pid' => $pid
        ];
        return $this->fetch('', $assign);
    }
}